package eureka.web;

import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import eureka.exceptions.DatabaseException;
import eureka.service.auction.IAuctionService;
import eureka.service.auction.impl.AuctionService;
import eureka.service.book.IBookService;
import eureka.service.book.impl.BookService;
import eureka.service.transaction.ITransactionService;
import eureka.service.transaction.impl.TransactionService;

/**
 * Application Lifecycle Listener implementation class WebJobTimer
 *
 */
@WebListener
public class WebJobTimer implements ServletContextListener {

	private Timer timer1 = null; 
	private Timer timer2 = null; 
	private Timer timer3 = null; 
	
    /**
     * Default constructor. 
     */
    public WebJobTimer() {
    	super();
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
    	timer1.cancel();
    	timer2.cancel();
    	timer3.cancel();
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
    	timer1 = new Timer(true);
    	timer1.schedule(new AutoUpdateBookStateJob(), 0, 6 * 3000000); // 5 * 60 * 1000
    	timer2 = new Timer(true);
    	timer2.schedule(new AutoUpdateTransactionStateJob(), 0, 6 * 3000000); // 5 * 60 * 1000
    	timer3 = new Timer(true);
    	timer3.schedule(new AutoUpdateAuctionStateJob(), 0, 6 * 3000000); // 5 * 60 * 1000
    }
    
    public class AutoUpdateBookStateJob extends TimerTask{
    	private IBookService bookService = new BookService();
    	 
        @Override 
        public void run() {
        	try {
        		bookService.refreshBooks(5, 20);
			} catch (DatabaseException e) {
				//e.printStackTrace();
			}
        }
    }
    
    public class AutoUpdateTransactionStateJob extends TimerTask{
    	private ITransactionService transactionService = new TransactionService();

        @Override 
        public void run() {
        	try {
				transactionService.refreshTransactions(5, 20);
			} catch (DatabaseException e) {
				//e.printStackTrace();
			}
        }
    }
    
    public class AutoUpdateAuctionStateJob extends TimerTask{
    	private IAuctionService auctionService = new AuctionService();

        @Override 
        public void run() {
        	try {
        		auctionService.refreshAuctions(5, 20);
			} catch (DatabaseException e) {
				//e.printStackTrace();
			}
        }
    }
}

